package com.ssm.opa.common.base.log;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Properties;

/**
 * 日志初始化
 */
public class LogInitListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogInitListener.class);


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 载入logback配置
        initLogger();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // context destroyed
    }

    private void initLogger() {
        String logbackConfigLocation;
        try {
        	 Resource resourceSetting = new ClassPathResource("main-setting.properties");
             Properties properties = PropertiesLoaderUtils.loadProperties(resourceSetting);
             logbackConfigLocation = "log/logback_" + properties.getProperty("envName") + ".xml";
        } catch (Exception ex) {
            throw new RuntimeException("can't loading main-setting.properties file from classpath.", ex);
        }

        try {
            Resource resource = new ClassPathResource(logbackConfigLocation);
            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            loggerContext.reset();
            JoranConfigurator joranConfigurator = new JoranConfigurator();
            joranConfigurator.setContext(loggerContext);
            joranConfigurator.doConfigure(resource.getInputStream());
            LOGGER.info("logback configure file loaded. filepath={}", resource.getURI());
        } catch (Exception e) {
            LOGGER.error("can't loading logback configure file. classpath:" + logbackConfigLocation, e);
        }
    }
}
